package com.huanglj.taobaounion.presenter.implement;

import com.huanglj.taobaounion.model.api.Api;
import com.huanglj.taobaounion.model.domain.OnSellResult;
import com.huanglj.taobaounion.presenter.IOnSellPagePresenter;
import com.huanglj.taobaounion.utils.LogUtil;
import com.huanglj.taobaounion.utils.RetrofitManager;
import com.huanglj.taobaounion.utils.UrlUtils;
import com.huanglj.taobaounion.view.IOnSellCallBack;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.huanglj.taobaounion.utils.Contants.SELL_PAGE;

public class OnSellPresenterImpl implements IOnSellPagePresenter {
    private static final String TAG = "OnSellPresenterImpl";

    private int mCurrentPage = SELL_PAGE;

    private final Api mApi;
    private IOnSellCallBack mCallBack = null;

    public OnSellPresenterImpl(){
        mApi = RetrofitManager.getInstance().getRetrofit().create(Api.class);
    }
    @Override
    public void getOnSellContent() {
        getSellContent(mCurrentPage);
    }

    private void getSellContent(int currentPage) {
        if (mCallBack != null) {
            mCallBack.onLoading();
        }
        String sellUrl = UrlUtils.getSellPath(mCurrentPage);
        mApi.getSellResult(sellUrl).enqueue(new Callback<OnSellResult>() {
            @Override
            public void onResponse(Call<OnSellResult> call, Response<OnSellResult> response) {
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    OnSellResult body = response.body();
                    if (mCallBack!=null) {
                        if (body.getData().getTbk_dg_optimus_material_response().getResult_list().getMap_data()!= null) {
                            mCallBack.onLoaded(body);
                        }else {
                            mCallBack.onEmpty();
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<OnSellResult> call, Throwable t) {
                LogUtil.d(TAG,"网络通信异常  " + t.toString());
                if (mCallBack != null) {
                    mCallBack.onError(t.toString());
                }
                if (mCurrentPage!=1) {
                    mCurrentPage--;
                }
            }
        });
    }

    @Override
    public void reLoad() {

    }

    @Override
    public void loaderMore() {
        mCurrentPage++;
        getSellContent(mCurrentPage);
    }

    @Override
    public void registerViewCallBack(IOnSellCallBack callBack) {
        mCallBack = callBack;
    }

    @Override
    public void unregisterViewCallBack(IOnSellCallBack callBack) {
        mCallBack = null;
    }
}
